//
//  SingleChatViewController.m
//  EnjoyAll
//
//  Created by 王晓冰 on 2017/10/27.
//  Copyright © 2017年 张雷. All rights reserved.
//

#import "SingleChatViewController.h"
#import "GroupInfoViewController.h"

@interface SingleChatViewController ()<EaseMessageViewControllerDelegate,EaseMessageViewControllerDataSource,EMClientDelegate,UIAlertViewDelegate>
{
    UIMenuItem *_copyMenuItem;
    UIMenuItem *_deleteMenuItem;
    UIMenuItem *_transpondMenuItem;
    UIMenuItem *_recallItem;
}

@property (nonatomic,strong)NSArray *numberSArr;

@end

@implementation SingleChatViewController
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

//    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = self.groupName;
    self.delegate = self;
    self.dataSource = self;
    [self _setupBarButtonItem];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteAllMessages:) name:@"RemoveAllMessages" object:nil];
    NSData *data = [[NSUserDefaults standardUserDefaults]valueForKey:@"numberArr"];
    self.numberSArr = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    
//    删除底部语音和视频
    [self.chatBarMoreView removeItematIndex:4];
    [self.chatBarMoreView removeItematIndex:3];
}

- (void)tableViewDidTriggerHeaderRefresh {
    //子类需要重写此方法
    [super tableViewDidTriggerHeaderRefresh];
}

- (void)_setupBarButtonItem
{
// EMConversationTypeChat
    //删除单聊会话
    if (self.conversation.type == 0) {
        UIButton *clearButton = [UIButton buttonWithType:UIButtonTypeCustom];
        
        clearButton.frame = CGRectMake(0, 0, 40, 40);
        
        [clearButton setImage:[UIImage imageNamed:@"clean"] forState:UIControlStateNormal];
        [clearButton addTarget:self action:@selector(deleteAllMessages:) forControlEvents:UIControlEventTouchUpInside];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:clearButton];
    }
    if (self.conversation.type == 1) {
        UIButton *groupButton = [UIButton buttonWithType:UIButtonTypeCustom];
        
        groupButton.frame = CGRectMake(0, 0, 30, 30);
        
        [groupButton setImage:[UIImage imageNamed:@"qunziliao_i"] forState:UIControlStateNormal];

        [groupButton addTarget:self action:@selector(detailOfGroup) forControlEvents:UIControlEventTouchUpInside];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:groupButton];
    }
    
}

- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}

- (void)deleteAllMessages:(id)sender
{
//    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"确定删除" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
//    [alertView show];
    
    self.messageTimeIntervalTag = -1;
    
    //删除该会话所有消息，同时清除内存和数据库中的消息
    
    [self.conversation deleteAllMessages:nil];
    [self.messsagesSource removeAllObjects];
    [self.dataArray removeAllObjects];
    [self.tableView reloadData];
}

- (void)detailOfGroup{
    
    NSString *conversationId = self.conversation.conversationId;
    EMGroup *group = [[EMClient sharedClient].groupManager getGroupSpecificationFromServerWithId:conversationId error:nil];
    
    GroupInfoViewController *InfoOfGroup = [[GroupInfoViewController alloc] init];
//    InfoOfGroup.groupName = self.navigationItem.title;
    //判断账号是否是管理员
    NSString *user = [DataCenter shareInstence].loginName;
    if ([group.owner isEqualToString:user]) {
        InfoOfGroup.isAdmin = YES;
    }else{
        InfoOfGroup.isAdmin = NO;
    }
    InfoOfGroup.conversationId = conversationId;
    [self.navigationController pushViewController:InfoOfGroup animated:YES];  
    
}



#pragma mark - EaseMessageViewControllerDelegate

- (BOOL)messageViewController:(EaseMessageViewController *)viewController
   canLongPressRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (BOOL)messageViewController:(EaseMessageViewController *)viewController
   didLongPressRowAtIndexPath:(NSIndexPath *)indexPath
{
    id object = [self.dataArray objectAtIndex:indexPath.row];
    if (![object isKindOfClass:[NSString class]]) {
        EaseMessageCell *cell = (EaseMessageCell *)[self.tableView cellForRowAtIndexPath:indexPath];
        if ([cell isKindOfClass:[EaseMessageCell class]]) {
            [cell becomeFirstResponder];
            self.menuIndexPath = indexPath;
            [self showMenuViewController:cell.bubbleView andIndexPath:indexPath messageType:cell.model.bodyType];
        }
    }
    return YES;
}

- (void)messageViewController:(EaseMessageViewController *)viewController
  didSelectAvatarMessageModel:(id<IMessageModel>)messageModel {

    NSLog(@"选中头像");
}

//获取要@的对象
//- (void)messageViewController:(EaseMessageViewController *)viewController
//               selectAtTarget:(EaseSelectAtTargetCallback)selectedCallback
//{
//    _selectedCallback = selectedCallback;
//    EMGroup *chatGroup = nil;
//    NSArray *groupArray = [[EMClient sharedClient].groupManager getJoinedGroups];
//    for (EMGroup *group in groupArray) {
//        if ([group.groupId isEqualToString:self.conversation.conversationId]) {
//            chatGroup = group;
//            break;
//        }
//    }
//
//    if (chatGroup == nil) {
//        chatGroup = [EMGroup groupWithId:self.conversation.conversationId];
//    }
//
//    if (chatGroup) {
//        if (!chatGroup.occupants) {
//            __weak ChatViewController* weakSelf = self;
//            [self showHudInView:self.view hint:@"Fetching group members..."];
//            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//                EMError *error = nil;
//                EMGroup *group = [[EMClient sharedClient].groupManager getGroupSpecificationFromServerWithId:chatGroup.groupId error:&error];
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    __strong ChatViewController *strongSelf = weakSelf;
//                    if (strongSelf) {
//                        [strongSelf hideHud];
//                        if (error) {
//                            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error" message:[NSString stringWithFormat:@"Fetching group members failed [%@]", error.errorDescription] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//                            [alertView show];
//                        }
//                        else {
//                            NSMutableArray *members = [group.occupants mutableCopy];
//                            NSString *loginUser = [EMClient sharedClient].currentUsername;
//                            if (loginUser) {
//                                [members removeObject:loginUser];
//                            }
//                            if (![members count]) {
//                                if (strongSelf.selectedCallback) {
//                                    strongSelf.selectedCallback(nil);
//                                }
//                                return;
//                            }
//                            ContactSelectionViewController *selectController = [[ContactSelectionViewController alloc] initWithContacts:members];
//                            selectController.mulChoice = NO;
//                            selectController.delegate = self;
//                            [self.navigationController pushViewController:selectController animated:YES];
//                        }
//                    }
//                });
//            });
//        }
//        else {
//            NSMutableArray *members = [chatGroup.occupants mutableCopy];
//            NSString *loginUser = [EMClient sharedClient].currentUsername;
//            if (loginUser) {
//                [members removeObject:loginUser];
//            }
//            if (![members count]) {
//                if (_selectedCallback) {
//                    _selectedCallback(nil);
//                }
//                return;
//            }
//            ContactSelectionViewController *selectController = [[ContactSelectionViewController alloc] initWithContacts:members];
//            selectController.mulChoice = NO;
//            selectController.delegate = self;
//            [self.navigationController pushViewController:selectController animated:YES];
//        }
//    }
//}

#pragma mark - EaseMessageViewControllerDataSource
/*!
 @method
 @brief 将EMMessage类型转换为符合<IMessageModel>协议的类型
 @discussion 将EMMessage类型转换为符合<IMessageModel>协议的类型,设置用户信息,消息显示用户昵称和头像
 @param viewController 当前消息视图
 @param EMMessage 聊天消息对象类型
 @result 返回<IMessageModel>协议的类型
 */
//具体样例：
- (id<IMessageModel>)messageViewController:(EaseMessageViewController *)viewController
                           modelForMessage:(EMMessage *)message
{
//    NSLog(@"%@",message.from);
    
    NSString *titleName = [Tool getHeadNameWithArr:self.numberSArr withString:message.from];
    if (titleName.length>2) {
        titleName = [titleName substringFromIndex:1];
    }
    
    //用户可以根据自己的用户体系，根据message设置用户昵称和头像
    id<IMessageModel> model = nil;
    model = [[EaseMessageModel alloc] initWithMessage:message];
    
        UILabel *label = [UILabel labelWithFrame:CGRectMake(0, 0, 40, 40) Font:FONT(13) TextColor:KWhiteColor];
        label.textAlignment = 1;
        label.text = titleName;
        label.textColor = KWhiteColor;
        label.backgroundColor = [UIColor colorWithHexString:@"2c9ae8"];
        UIImage *img = [Tool imageWithUIView:label];
        //头像
        model.avatarImage = img;

    model.nickname = titleName;//用户昵称
    return model;
}

//跟他没关系
- (void)messageViewControllerMarkAllMessagesAsRead:(EaseMessageViewController *)viewController
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"setupUnreadMessageCount" object:nil];
}

#pragma mark - EaseMob

#pragma mark - EMClientDelegate

- (void)userAccountDidLoginFromOtherDevice
{
    if ([self.imagePicker.mediaTypes count] > 0 && [[self.imagePicker.mediaTypes objectAtIndex:0] isEqualToString:(NSString *)kUTTypeMovie]) {
        [self.imagePicker stopVideoCapture];
    }
}

- (void)userAccountDidRemoveFromServer
{
    if ([self.imagePicker.mediaTypes count] > 0 && [[self.imagePicker.mediaTypes objectAtIndex:0] isEqualToString:(NSString *)kUTTypeMovie]) {
        [self.imagePicker stopVideoCapture];
    }
}

- (void)userDidForbidByServer
{
    if ([self.imagePicker.mediaTypes count] > 0 && [[self.imagePicker.mediaTypes objectAtIndex:0] isEqualToString:(NSString *)kUTTypeMovie]) {
        [self.imagePicker stopVideoCapture];
    }
}

#pragma mark - EMChatManagerDelegate

//消息撤回
- (void)messagesDidRecall:(NSArray *)aMessages
{
    for (EMMessage *msg in aMessages) {
        if (![self.conversation.conversationId isEqualToString:msg.conversationId]){
            continue;
        }
        
        NSString *text;
        if ([msg.from isEqualToString:[EMClient sharedClient].currentUsername]) {
            text = [NSString stringWithFormat:NSLocalizedString(@"message.recall", @"You recall a message")];
        } else {
            text = [NSString stringWithFormat:NSLocalizedString(@"message.recallByOthers", @"%@ recall a message"),msg.from];
        }
        
        [self _recallWithMessage:msg text:text isSave:NO];
    }
}

#pragma mark - action
//撤回
- (void)recallMenuAction:(id)sender
{
    if (self.menuIndexPath && self.menuIndexPath.row > 0) {
        __weak typeof(self) weakSelf = self;
        id<IMessageModel> model = [self.dataArray objectAtIndex:self.menuIndexPath.row];
        [[EMClient sharedClient].chatManager recallMessage:model.message
                                                completion:^(EMMessage *aMessage, EMError *aError) {
                                                    if (!aError) {
                                                        [weakSelf _recallWithMessage:aMessage text:NSLocalizedString(@"message.recall", @"You recall a message") isSave:YES];
                                                    } else {
                                                        [weakSelf showHint:[NSString stringWithFormat:NSLocalizedString(@"recallFailed", @"Recall failed:%@"), aError.errorDescription]];
                                                    }
                                                    weakSelf.menuIndexPath = nil;
                                                }];
    }
}



- (void)copyMenuAction:(id)sender
{
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    if (self.menuIndexPath && self.menuIndexPath.row > 0) {
        id<IMessageModel> model = [self.dataArray objectAtIndex:self.menuIndexPath.row];
        pasteboard.string = model.text;
    }
    
    self.menuIndexPath = nil;
}

- (void)deleteMenuAction:(id)sender
{
    if (self.menuIndexPath && self.menuIndexPath.row > 0) {
        id<IMessageModel> model = [self.dataArray objectAtIndex:self.menuIndexPath.row];
        NSMutableIndexSet *indexs = [NSMutableIndexSet indexSetWithIndex:self.menuIndexPath.row];
        NSMutableArray *indexPaths = [NSMutableArray arrayWithObjects:self.menuIndexPath, nil];
        
        [self.conversation deleteMessageWithId:model.message.messageId error:nil];
        [self.messsagesSource removeObject:model.message];
        
        if (self.menuIndexPath.row - 1 >= 0) {
            id nextMessage = nil;
            id prevMessage = [self.dataArray objectAtIndex:(self.menuIndexPath.row - 1)];
            if (self.menuIndexPath.row + 1 < [self.dataArray count]) {
                nextMessage = [self.dataArray objectAtIndex:(self.menuIndexPath.row + 1)];
            }
            if ((!nextMessage || [nextMessage isKindOfClass:[NSString class]]) && [prevMessage isKindOfClass:[NSString class]]) {
                [indexs addIndex:self.menuIndexPath.row - 1];
                [indexPaths addObject:[NSIndexPath indexPathForRow:(self.menuIndexPath.row - 1) inSection:0]];
            }
        }
        
        [self.dataArray removeObjectsAtIndexes:indexs];
        [self.tableView beginUpdates];
        [self.tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];
        [self.tableView endUpdates];
        
        if ([self.dataArray count] == 0) {
            self.messageTimeIntervalTag = -1;
        }
    }
    
    self.menuIndexPath = nil;
}

#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.cancelButtonIndex != buttonIndex) {
//        self.messageTimeIntervalTag = -1;
//
//            //删除该会话所有消息，同时清除内存和数据库中的消息
//
//                [self.conversation deleteAllMessages:nil];
//                [self.messsagesSource removeAllObjects];
//                [self.dataArray removeAllObjects];
//                [self.tableView reloadData];

    }
}

#pragma mark - private

- (void)showMenuViewController:(UIView *)showInView
                  andIndexPath:(NSIndexPath *)indexPath
                   messageType:(EMMessageBodyType)messageType
{
    if (self.menuController == nil) {
        self.menuController = [UIMenuController sharedMenuController];
    }
    
    if (_deleteMenuItem == nil) {
        _deleteMenuItem = [[UIMenuItem alloc] initWithTitle:@"删除" action:@selector(deleteMenuAction:)];
    }
    
    if (_copyMenuItem == nil) {
        _copyMenuItem = [[UIMenuItem alloc] initWithTitle:@"复制" action:@selector(copyMenuAction:)];
    }
    
//    if (_transpondMenuItem == nil) {
//        _transpondMenuItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"transpond", @"Transpond") action:@selector(transpondMenuAction:)];
//    }
    
    if (_recallItem == nil) {
//        _recallItem = [[UIMenuItem alloc] initWithTitle:@"撤回" action:@selector(recallMenuAction:)];
    }
    
    NSMutableArray *items = [NSMutableArray array];
    
    if (messageType == EMMessageBodyTypeText) {
        [items addObject:_copyMenuItem];
//        [items addObject:_transpondMenuItem];
        [items addObject:_deleteMenuItem];
    } else if (messageType == EMMessageBodyTypeImage || messageType == EMMessageBodyTypeVideo) {
//        [items addObject:_transpondMenuItem];
        [items addObject:_deleteMenuItem];
    } else {
        [items addObject:_deleteMenuItem];
    }
    
    id<IMessageModel> model = [self.dataArray objectAtIndex:self.menuIndexPath.row];
    if (model.isSender) {
//        [items addObject:_recallItem];
    }
    
    [self.menuController setMenuItems:items];
    [self.menuController setTargetRect:showInView.frame inView:showInView.superview];
    [self.menuController setMenuVisible:YES animated:YES];
}

- (void)_recallWithMessage:(EMMessage *)msg text:(NSString *)text isSave:(BOOL)isSave
{
    EMMessage *message = [EaseSDKHelper getTextMessage:text to:msg.conversationId messageType:msg.chatType messageExt:@{@"em_recall":@(YES)}];
    message.isRead = YES;
    [message setTimestamp:msg.timestamp];
    [message setLocalTime:msg.localTime];
    
    id<IMessageModel> newModel = [[EaseMessageModel alloc] initWithMessage:message];
    __block NSUInteger index = NSNotFound;
    [self.dataArray enumerateObjectsUsingBlock:^(EaseMessageModel *model, NSUInteger idx, BOOL *stop){
        if ([model conformsToProtocol:@protocol(IMessageModel)]) {
            if ([msg.messageId isEqualToString:model.message.messageId])
            {
                index = idx;
                *stop = YES;
            }
        }
    }];
    if (index != NSNotFound)
    {
        __block NSUInteger sourceIndex = NSNotFound;
        [self.messsagesSource enumerateObjectsUsingBlock:^(EMMessage *message, NSUInteger idx, BOOL *stop){
            if ([message isKindOfClass:[EMMessage class]]) {
                if ([msg.messageId isEqualToString:message.messageId])
                {
                    sourceIndex = idx;
                    *stop = YES;
                }
            }
        }];
        if (sourceIndex != NSNotFound) {
            [self.messsagesSource replaceObjectAtIndex:sourceIndex withObject:newModel.message];
        }
        [self.dataArray replaceObjectAtIndex:index withObject:newModel];
        [self.tableView reloadData];
    }
    
    if (isSave) {
        [self.conversation insertMessage:message error:nil];
    }
}


@end
